<?php

namespace app\admin\controller\goods;

use app\common\controller\AdminController;
use app\common\model\GoodsLibrary;
use app\common\model\GoodsLibraryGoodsRelation;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="商品库关联商品表")
 */
class LibraryGoodsRelation extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\GoodsLibraryGoodsRelation();

    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $libraryId = input('library_id', 0, 'intval');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where, $extra) = $this->buildTableParames(['goods_name']);
            if ($libraryId) {
                array_unshift($where, ['ggr.goods_library_id', '=', $libraryId]);
            }
            if (isset($extra['goods_name'])) {
                $where[] = ['g.name', 'like', '%' . $extra['goods_name'] . '%'];
            }
            $where[] = ['g.delete_time', '=', 0];
            try {
                $count = $this->model->alias('ggr')
                    ->leftJoin('goods g', 'g.id=ggr.goods_id')
                    ->leftJoin('goods_category gc', 'g.category_id = gc.id')
                    ->where($where)
                    ->count();
                $list  = $this->model->alias('ggr')
                    ->leftJoin('goods g', 'g.id=ggr.goods_id')
                    ->leftJoin('goods_category gc', 'g.category_id = gc.id')
                    ->leftJoin('shop s', 'g.shop_id = s.id')
                    ->where($where)
                    ->field('ggr.*,g.name as goods_name,g.img,g.is_sale,g.id as goods_id,gc.name as category_name,g.show_price,s.name as shop_name')
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $v) {
                    if (!$v['shop_name']) {
                        $v['shop_name'] = '平台';
                    }
                }
            } catch (\Exception $e) {
                var_dump($e->getMessage());
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('library_id', $libraryId);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $libraryId = input('library_id', 0, 'intval');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'goods_id|商品' => 'require'
            ];
            $this->validate($post, $rule);
            try {
                $insertData = [];
                $goodsId    = explode(',', input('goods_id'));
                foreach ($goodsId as $gid) {
                    $insertData[] = [
                        'goods_library_id' => $libraryId,
                        'goods_id'         => $gid,
                        'status'           => input('status', 0, 'intval')
                    ];
                }
                $save = (new GoodsLibraryGoodsRelation())->saveAll($insertData);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功');
        }
        $library = GoodsLibrary::where('id', $libraryId)->field('id,name')->find();
        $this->assign('library', $library);
        $existGoodsId = implode(',', GoodsLibraryGoodsRelation::where('goods_library_id', $libraryId)->column('goods_id'));
        $this->assign('exist_goods_id', $existGoodsId);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'goods_id|商品' => 'require'
            ];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $library = GoodsLibrary::where('id', $row['goods_library_id'])->field('id,name')->find();
        $this->assign('library', $library);
        return $this->fetch();
    }

}